<?php

/**
* 收藏文章，必须将collection()放在loop内
*/

function collection(){
	$post_id = get_the_ID();
	$user_id = get_current_user_id();
	$url = get_url();//注意，必须要get_url.php支持
	$nonce = wp_create_nonce('my-nonce-collection');
	
	$exp = get_user_meta($user_id,'user_collection',true);
	$exp = explode(',',$exp);
	if(in_array($post_id,$exp))
		echo'<a href="?action=del_collection&uid='.$user_id.'&pid='.$post_id.'&_wpnonce='.$nonce.'&url='.urlencode($url).'">'.get_interpret('取消收藏').'</a>';
	else
		echo '<a href="?action=collection&uid='.$user_id.'&pid='.$post_id.'&_wpnonce='.$nonce.'&url='.urlencode($url).'">'.get_interpret('收藏').'</a>';
}

/**
* 接下来的代码将执行collection()点击之后的数据库写入动作
* 其中get_url函数需要the_url.php支持
*/

function collection_successed(){
	$redirect = get_bloginfo('url').'/author';
	if(@$_REQUEST['action'] == 'collection' 
		&& isset($_REQUEST['uid']) 
		&& isset($_REQUEST['pid']) 
		&& isset($_REQUEST['_wpnonce']) 
		&& isset($_REQUEST['url'])
	){
		if(!is_user_logged_in() && get_url() != $redirect){
			wp_redirect($redirect);
			exit;
		}
		$user_id = $_REQUEST['uid'];
		$post_id = $_REQUEST['pid'];
		$url = $_REQUEST['url'];
		$nonce = $_REQUEST['_wpnonce'];
		if(!wp_verify_nonce($nonce,'my-nonce-collection'))
			wp_die(__('Bad Work!','').'<a href="javascript:window.history.go(-1);">'.get_interpret('返回').'</a>');
		$user_collection = get_user_meta($user_id,'user_collection',true);
		if($user_collection == '')$user_collection = $post_id;
		else $user_collection = $user_collection.','.$post_id;
		update_user_meta($user_id,'user_collection',$user_collection);
		wp_redirect($url.'#post-'.$post_id);
		exit();
	}
	if(@$_REQUEST['action'] == 'del_collection' 
		&& isset($_REQUEST['uid']) 
		&& isset($_REQUEST['pid']) 
		&& isset($_REQUEST['_wpnonce']) 
		&& isset($_REQUEST['url'])
	){
		if(!is_user_logged_in() && get_url() != $redirect){
			wp_redirect($redirect);
			exit;
		}
		$user_id = $_REQUEST['uid'];
		$post_id = $_REQUEST['pid'];
		$url = $_REQUEST['url'];
		$nonce = $_REQUEST['_wpnonce'];
		if(!wp_verify_nonce($nonce,'my-nonce-collection'))
			wp_die(__('Bad Work!','').'<a href="javascript:window.history.go(-1);">'.get_interpret('返回').'</a>');
		$user_collection = get_user_meta($user_id,'user_collection',true);
		$user_collection = explode(',',$user_collection);
		$user_collection = array_unique($user_collection);
		if(($key = array_search($post_id,$user_collection))){
			unset($user_collection[$key]);
		}
		$user_collection = implode(',',$user_collection);
		update_user_meta($user_id,'user_collection',$user_collection);
		wp_redirect($url.'#collection-'.$post_id);
		exit();
	}
}
add_action('wp','collection_successed');
